#include "chatwindow.h"
#include "ui_chatwindow.h"
#include "clientdatabase.h"
#include "chatrecord.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QByteArray>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QFile>
#include <QFileInfo>
#include <QMessageBox>



chatWindow::chatWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::chatWindow)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint);
    ui->label_2->setText(friname);

    tcpSocket=new QTcpSocket(this);
    tcpSocket->connectToHost("localhost",8022);
    connect(tcpSocket, &QTcpSocket::connected, this, &chatWindow::slotConnected);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &chatWindow::slotDisconnected);
    connect(tcpSocket, &QTcpSocket::readyRead, this, &chatWindow::onReadyRead);

    QJsonObject dataObject;
    dataObject["sendtype"]="chat_start";
    dataObject["selfname"]=selfname;
    dataObject["selfaccount"]=selfaccount;
    dataObject["friaccount"]=friaccount;
    dataObject["friname"]=friname;
    QJsonDocument dataDocument(dataObject);
    QByteArray jsonData=dataDocument.toJson();
    tcpSocket->write(jsonData);

    ui->sendtextLine->installEventFilter(this);  //设置完后自动调用其eventFilter函数

}

chatWindow::chatWindow(const QString&selfnam,const QString&selfacc,const QString&time):
    ui(new Ui::chatWindow){
    QWidget *parent = nullptr;
    selfname=selfnam;
    selfaccount=selfacc;
    chattype="groupchat";
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint);
    ui->label_2->setText(tr("一起聊天吧！"));

    tcpSocket=new QTcpSocket(this);
    tcpSocket->connectToHost("localhost",8022);
    connect(tcpSocket, &QTcpSocket::connected, this, &chatWindow::slotConnected);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &chatWindow::slotDisconnected);
    connect(tcpSocket, &QTcpSocket::readyRead, this, &chatWindow::onReadyRead);

    QJsonObject dataObject;
    dataObject["sendtype"]="groupchat_start";
    dataObject["selfname"]=selfnam;
    dataObject["selfaccount"]=selfacc;
    dataObject["entertime"]=time;
    QJsonDocument dataDocument(dataObject);
    QByteArray jsonData=dataDocument.toJson();
    tcpSocket->write(jsonData);
    ui->sendtextLine->installEventFilter(this);
}

chatWindow::chatWindow(const QString&selfnam,const QString&selfacc,const QString&frinam,const QString&friacc):
    ui(new Ui::chatWindow)
{
    QWidget *parent = nullptr;
    selfname=selfnam;
    selfaccount=selfacc;
    friname=frinam;
    friaccount=friacc;
    chattype="singlechat";
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint);
    ui->label_2->setText(friname);

    tcpSocket=new QTcpSocket(this);
    tcpSocket->connectToHost("localhost",8022);
    connect(tcpSocket, &QTcpSocket::connected, this, &chatWindow::slotConnected);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &chatWindow::slotDisconnected);
    connect(tcpSocket, &QTcpSocket::readyRead, this, &chatWindow::onReadyRead);

    QJsonObject dataObject;
    dataObject["sendtype"]="chat_start";
    dataObject["selfname"]=selfname;
    dataObject["selfaccount"]=selfaccount;
    dataObject["friaccount"]=friaccount;
    dataObject["friname"]=friname;
    QJsonDocument dataDocument(dataObject);
    QByteArray jsonData=dataDocument.toJson();
    tcpSocket->write(jsonData);

    ui->sendtextLine->installEventFilter(this);
}

chatWindow::~chatWindow()
{
    delete ui;
    delete tcpSocket;
}

void chatWindow::getselfaccount(const QString &acc){
    selfaccount=acc;
}

void chatWindow::getfriaccount(const QString &acc){
    friaccount=acc;
}

//发送按钮
void chatWindow::on_pushButton_clicked()
{
    if(ui->sendtextLine->document()->isEmpty()){
        return;
    }
     sendChatMessage(ui->sendtextLine->toPlainText());
    ui->sendtextLine->clear();
}

void chatWindow::slotConnected(){
    qDebug()<<"调用 chatWindow 的slotConnected函数"<<endl;
}

void chatWindow::slotDisconnected(){
    qDebug()<<"调用 chatWindow 的slotDisconnected函数"<<endl;
}

void chatWindow::onReadyRead(){
    qDebug()<<"调用 chatWindow 的onReadyRead函数"<<endl;
    QByteArray jsonData=tcpSocket->readAll();
    QJsonDocument dataDocument=QJsonDocument::fromJson(jsonData);
    if(!dataDocument.isNull()&&dataDocument.isObject()){
        QJsonObject dataObject=dataDocument.object();
        if(dataObject["returntype"].toString()=="singlechat"){
            QString username=dataObject["selfname"].toString();
            qDebug()<<"selfname"<<username<<endl;
            QString message=dataObject["message"].toString();
            QString chatMessage=QString("%1:%2").arg(username,message);
            qDebug()<<"test  show message"<<endl;
            ui->showText->append(chatMessage);
            if(dataObject["selfaccount"].toString()!=selfaccount)
           clientDataBase::getInstance()->add_singlechat_record(selfaccount,friaccount,friname,message);
        }
        else
            if(dataObject["returntype"].toString()=="groupchat"){
                QString username=dataObject["selfname"].toString();
                QString message=dataObject["message"].toString();
                QString chatMessage=QString("%1:%2").arg(username,message);
             //   if(dataObject["selfaccount"].toString()!=selfaccount)
      //          clientDataBase::getInstance()->add_groupchat_record("group_chat",username,message);
                ui->showText->append(chatMessage);
        }
        else
             if(dataObject["returntype"].toString()=="groupchat_start"){
                 QString username=dataObject["selfname"].toString();
                 QString message="enter the room at "+dataObject["entertime"].toString();
                 QString chatMessage=QString("%1:%2").arg(username,message);
                 ui->showText->append(chatMessage);
                }
         }
}

void chatWindow::sendChatMessage(const QString &message){
    qDebug()<<"调用 chatWindow 的sendChatMessage函数"<<endl;
    QJsonObject dataObject;
    if(chattype=="singlechat"){
    dataObject["sendtype"]="singlechat";
    dataObject["selfname"]=selfname;
    dataObject["selfaccount"]=selfaccount;
    dataObject["friaccount"]=friaccount;
    dataObject["message"]=message;
    dataObject["friname"]=friname;
    clientDataBase::getInstance()->add_singlechat_record(selfaccount,friaccount,selfname,message);

   }
     else
        if(chattype=="groupchat"){
            dataObject["sendtype"]="groupchat";
            dataObject["selfaccount"]=selfaccount;
            dataObject["selfname"]=selfname;
            dataObject["message"]=message;
            clientDataBase::getInstance()->add_groupchat_record("group_chat",selfname,message);
    //        clientDataBase::getInstance()->add_groupchat_record("group_chat",username,message);

    }
    QJsonDocument dataDocument(dataObject);
    QByteArray jsonData=dataDocument.toJson();
    tcpSocket->write(jsonData);

}

void chatWindow::getnames(const QString &selfname, const QString &friname){
    this->selfname=selfname;
    this->friname=friname;
}

void chatWindow::on_toolButton_clicked()
{
    this->showMinimized();
}

void chatWindow::on_toolButton_2_clicked()
{
    tcpSocket->abort();
    this->close();
}

void chatWindow::mousePressEvent(QMouseEvent *event)
{
    this->windowPos = this->pos();       // 获得部件当前位置
    this->mousePos = event->globalPos(); // 获得鼠标位置
    this->dPos = mousePos - windowPos;   // 移动后部件所在的位置
}

void chatWindow::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos() - this->dPos);
}

//实现事件过滤器，达到按enter键就发送消息的效果
bool chatWindow::eventFilter(QObject *watched, QEvent *event){
    if(watched==ui->sendtextLine){
        //获取按键信号
        if(event->type()==QEvent::KeyPress){
            QKeyEvent *k=static_cast<QKeyEvent *>(event);
            if(k->key()==Qt::Key_Return){      //选定回车键
                on_pushButton_clicked();       //连接槽信号
                return true;
            }
        }
    }
    return QWidget::eventFilter(watched,event);
}
void chatWindow::showmessage(const QString &message){
    ui->showText->append(message);
}

//删除聊天记录
void chatWindow::on_toolButton_4_clicked()
{
    if(chattype=="singlechat")
    clientDataBase::getInstance()->clear_singlechat_record(selfaccount,friaccount);
    else if(chattype=="groupchat")
        clientDataBase::getInstance()->clear_groupchat_record();
}

void chatWindow::on_toolButton_3_clicked()
{
    QVector<QString> sr;
   if(chattype=="groupchat"){
      chatRecord *cr=new chatRecord();
      cr->show();
   }
   else
       if(chattype=="singlechat"){
           chatRecord *cr=new chatRecord(selfname,friname,selfaccount,friaccount);
          cr->show();
       }

}



//发送文件按钮
//void chatWindow::on_toolButton_5_clicked()
//{
//    QString path=ui->sendtextLine->toPlainText();
//    QFile file(path);
//    if(file.exists()){
//        qDebug()<<"文件存在 273 chatwindow"<<endl;
//        QFileInfo info(path);
//        filename=info.fileName();
//        fileSize=info.size();
//        sendSize=0;

//        file.setFileName(path);

//        bool isOK=file.open(QIODevice::ReadOnly);
//        if(isOK==false){
//            qDebug()<<"文件未成功打开"<<endl;
//        }
//    }
//    else{
//        qDebug()<<"文件不存在  chatwindow"<<endl;
//        return;
//    }
//     QJsonObject dataObject;
//     dataObject["sendtype","sendfile"];
//     dataObject["filename",filename];
//     dataObject["filesize",fileSize];
//     QJsonDocument dataDocument(dataObject);
//     QByteArray jsonData=dataDocument.toJson();
//     qint64 len=tcpSocket->write(jsonData);
//     if(len>0){

//     }else{
//         qDebug()<<"发送文件信息失败"<<endl;
//         QMessageBox::warning(this,"消息提醒","发送文件失败", QMessageBox::NoButton, QMessageBox::Ok);

//     }





//}
